package com.jiyici.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

public class Utils {

    
    public static Bitmap scaleBitmp(Bitmap thumbnail,int w, int h)
	{
		
		if(thumbnail == null) return null;
		
		  Bitmap bitmap= null;
		  int  src_w = thumbnail.getWidth();
		  int  src_h = thumbnail.getHeight();
		  float scale_w = ((float)w)/src_w;
		  float  scale_h = ((float)h)/src_h;
		  float final_Scale = scale_w < scale_h?scale_w : scale_h;
		  Matrix  matrix = new Matrix();
		  matrix.postScale(final_Scale, final_Scale);
		  bitmap = Bitmap.createBitmap(thumbnail, 0, 0, src_w, src_h, matrix, true);
		  //thumbnail.recycle();
		  
		  return bitmap;
	}
    
    
    public static Bitmap drawViewIntoBitmap(View view,String path) {
		
		int w = view.getWidth();
		int h =view.getHeight();
		
		if(w ==0 || h == 0)
		{
			int w1 = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
			int h1 = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
			view.measure(w1, h1); 
			view.forceLayout();
			w =view.getMeasuredHeight(); 
			h =view.getMeasuredWidth(); 
		}
		
		Bitmap postcard = Bitmap.createBitmap(w, h,Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(postcard);
		Drawable bgDrawable =view.getBackground();
		if (bgDrawable!=null) 
		     bgDrawable.draw(canvas);
		view.draw(canvas);
		
		if(path!= null)
		{
			try {
				
				FileOutputStream out = new FileOutputStream(new File(path));
				if (postcard.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
					out.flush();
					out.close();
				}
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return postcard;
	}

    
    public static byte[] Bitmap2Bytes(Bitmap bm) {         
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    	return baos.toByteArray();
    }

//    public static void checkForUpdate(final Context context,final boolean needToast) {
//        if (!NetWorkUtil.haveInternet(context)) {
//            Utils.showNetworkSettingDialog(context);
//        }
//
//        final String versionInfo = getVersionInfo(context);
//        if (versionInfo != null) {
//            // if(mDialog == null){
//            // mDialog = new ProgressDialog(PostCardActivity.this);
//            // }
//            //
//            // mDialog.setMessage(getString(R.string.checking_newversion_waiting));
//            // CheckUpdateTask task = new CheckUpdateTask(true);
//            // task.execute(versionInfo);
//            new ServerAsyncTask(context) {
//
//                @Override
//                protected void onSuccess(PostcardResult result) {
//                    CheckNewData data = result.getCheckNewData();
//                    if (data.HasNewVersion) {
//                        doInfoNewVersion(context, data.HasNewVersion, data.Version, data.Url, data.Note);
//                    } else if(needToast){
//                        Toast.makeText(context, "已经是最新版本", Toast.LENGTH_SHORT).show();
//                    }
//                }
//
//                @Override
//                protected PostcardResult doRequest() {
//                	String channal = Utils.getChannal(context);
//                	//need send channal information to server
//                    return ServerFactory.getServer().checkNew(versionInfo, channal);
//                }
//            }.execute();
//        }
//    }

//    private static String getVersionInfo(Context context) {
//        String versionInfo = null;
//        PackageManager pm = context.getPackageManager();
//        try {
//            PackageInfo pi = pm.getPackageInfo("com.ilovepostcard", PackageManager.GET_ACTIVITIES);
//            //int versionCode = pi.versionCode;
//            String versionName = pi.versionName;
//            versionInfo = versionName;
//            Log.d(Constants.TAG, "version info = " + versionInfo);
//        } catch (NameNotFoundException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        return versionInfo;
//    }
//
//    private static void doInfoNewVersion(final Context context, boolean hasNewVersion, final String version, final String url, String note) {
//        if (hasNewVersion) {
//            StringBuffer sb = new StringBuffer();
//            sb.append(context.getString(R.string.newversion_info));
//            sb.append(version + "\n");
//            sb.append(note);
///*
//            new AlertDialog.Builder(context).setTitle(R.string.update_to_new_version).setMessage(sb.toString())
//                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                            doUpdateToNewVersion(context, url, version);
//                        }
//                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//
//                        }
//                    }).show();*/
//            
//            
//            final Dialog dialog = new Dialog(context, R.style.dialog);
//            // AlertDialog.Builder builder = new AlertDialog.Builder(context);
//
//            View view = View.inflate(context, R.layout.dialog_confirm, null);
//            TextView messageText = (TextView) view.findViewById(R.id.dialog_msg);
//            Button cancelButton = (Button)view.findViewById(R.id.dialog_cancel);
//            Button confirmButton = (Button)view.findViewById(R.id.dialog_confirm);
//            confirmButton.setText("立即更新");
//            messageText.setText(sb.toString());
//            
//            confirmButton.setOnClickListener(new View.OnClickListener() {
//                
//                @Override
//                public void onClick(View v) {
//                    dialog.dismiss();
//                    doUpdateToNewVersion(context, url, version);
//                }
//            });
//            
//            cancelButton.setOnClickListener(new View.OnClickListener() {
//                
//                @Override
//                public void onClick(View v) {
//                    dialog.dismiss();
//                }
//            });
//            
//            dialog.setContentView(view);
//
//            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//            int windowWidth = wm.getDefaultDisplay().getWidth();
//            Window dialogWindow = dialog.getWindow();
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            dialogWindow.setGravity(Gravity.CENTER);
//            lp.width = (int) (windowWidth * .75);
//            dialogWindow.setAttributes(lp);
//
//            dialog.setCanceledOnTouchOutside(true);
//            dialog.show();
//        } else {
//
//            new AlertDialog.Builder(context).setTitle(R.string.app_name).setMessage(R.string.newest_version)
//                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    }).show();
//        }
//    }
//
//    private static void doUpdateToNewVersion(Context context, String newVersionUrl, String newVersionStr) {
//
//        String status = Environment.getExternalStorageState();
//        if (status.equals(Environment.MEDIA_MOUNTED)) {
//            Intent intent = new Intent(context, com.ilovepostcard.GetNewVersionService.class);
//            intent.putExtra("url", newVersionUrl);
//            intent.putExtra("version_name", newVersionStr);
//            context.startService(intent);
//
//        } else {
//            Toast.makeText(context, R.string.no_sdcard, Toast.LENGTH_SHORT).show();
//        }
//
//    }
//    
//    public static void inviteFriends(final Context context) {
//        String[] items = new String[] { context.getString(R.string.add_by_email),
//                context.getString(R.string.add_by_sms) };
//        Utils.showChooseDialog(context, items, new Runnable[] {
//                new Runnable() {
//                    
//                    @Override
//                    public void run() {
//                    	
//                    	MobclickAgent.onEvent(context, Constants.COUNT_INVITE_MAIL);
//                        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
//
//                        intent.putExtra(
//                                android.content.Intent.EXTRA_SUBJECT,
//                                context.getString(R.string.email_invite_title));
//                        
//                        StringBuffer sb = new StringBuffer();
//                        sb.append(context.getString(R.string.email_invite_content));
//                        User user = UserController.getDetailUser(context);
//                        sb.append(user.Nickname);
//                        
//                        intent.putExtra(android.content.Intent.EXTRA_TEXT,sb.toString());
////                        MobclickAgent.onEvent(PostCardActivity.this, Constants.POSTCARD_INVITE_EMAIL);
//                        intent.setType("plain/text");
//                        context.startActivity(Intent.createChooser(intent,context.getString(R.string.mail_chooser)));
//                    }
//                }, 
//                new Runnable() {
//                    
//                    @Override
//                    public void run() {
//                    	
//                    	MobclickAgent.onEvent(context, Constants.COUNT_INVITE_SMS);
//                        Uri smsToUri = Uri.parse("smsto:");
//                        Intent mIntent = new Intent(
//                                android.content.Intent.ACTION_SENDTO,
//                                smsToUri);
//                        mIntent.putExtra("sms_body", context.getString(R.string.sms_invite_content));
////                        MobclickAgent.onEvent(PostCardActivity.this, Constants.POSTCARD_INVITE_SMS);
//                        context.startActivity(mIntent);
//                    }
//                }
//        });
//        
//    }

    /**
     * save integer data into sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param value
     */
    public static void setPreferenceIntData(Context context, String name, String key, int value) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    /**
     * save long data into sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param value
     */
    public static void setPreferenceLongData(Context context, String name, String key, long value) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(key, value);
        editor.commit();
    }

    /**
     * save boolean data into sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param value
     */
    public static void setPreferenceBooleanData(Context context, String name, String key, Boolean value) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * save string data into sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param value
     */
    public static void setPreferenceStringData(Context context, String name, String key, String value) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * get Int data from sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param defaultValue
     * @return
     */
    public static int getPreferenceData(Context context, String name, String key, int defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        return settings.getInt(key, defaultValue);

    }

    /**
     * get Long data from sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param defaultValue
     * @return
     */
    public static long getPreferenceData(Context context, String name, String key, long defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        return settings.getLong(key, defaultValue);

    }

    /**
     * get boolean data from sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getPreferenceData(Context context, String name, String key, boolean defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        return settings.getBoolean(key, defaultValue);

    }

    /**
     * get String data from sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getPreferenceData(Context context, String name, String key, String defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        return settings.getString(key, defaultValue);

    }
    
    /**
     * remove data from sharedPreference
     * 
     * @param context
     * @param name
     * @param key
     */
    public static void removePreference(Context context, String name, String key) {
    	SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = settings.edit();
        editor.remove(key);
        editor.commit();
    }

    /**
     * move the file to new destination
     * 
     * @param srcFile
     * @param destPath
     * @return
     */
    public static boolean MoveFile(File srcFile, String destPath) {
        // Destination directory
        File dir = new File(destPath);

        // Move file to new directory
        boolean success = srcFile.renameTo(new File(dir, srcFile.getName()));

        return success;
    }

    /**
     * see if the file is exist
     * 
     * @param path
     * @return
     */
    public static boolean isFileExist(String path) {
        if (path != null) {
            return new File(path).exists();
        } else {
            return false;
        }
    }
    
    public static void deleteFile(String path) {
        File file = new File(path);
        file.delete();
    }

    /**
     * convert byte[] to bitmap
     * 
     * @param bytes
     * @param opts
     * @return
     */
    public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }

    /**
     * change the bitmap size
     * 
     * @param bitmap
     * @return
     */
    public static Bitmap setBitmapSize(Bitmap bitmap, int newWidth, int newHeight) {

        if (bitmap == null)
            return null;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap newbitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.recycle();
        return newbitmap;
    }

    /**
     * round bitmap
     * 
     * @param bitmap
     * @param roundPx
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

        if (bitmap == null)
            return null;
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    public static Bitmap getRoundedCornerFrameBitmap(Bitmap bitmap, float roundPx) {

        if (bitmap == null)
            return null;

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        Rect rectL = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectFL = new RectF(rectL);

        Path path = new Path();
        path.addRoundRect(rectFL, roundPx, roundPx, android.graphics.Path.Direction.CCW);

        rectL = new Rect(1, 1, bitmap.getWidth() - 1, bitmap.getHeight() - 1);
        rectFL = new RectF(rectL);
        path.addRoundRect(rectFL, roundPx - 1, roundPx - 1, android.graphics.Path.Direction.CCW);
        path.setFillType(Path.FillType.EVEN_ODD);

        final Paint paintL = new Paint();
        paint.setColor(Color.BLACK);

        canvas.drawPath(path, paintL);

        return output;
    }

    /**
     * read image
     * 
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;

    }

    /**
     * get current time and return by default format or you appoint
     * 
     * @param format
     * @return
     */
    public static String getNow(String format) {
        if (null == format || "".equals(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = sdf.format(new Date());
        return date;
    }

    /**
     * convert the date from String to Date
     * 
     * @param _date
     *            the date you want to convert
     * @param format
     *            the DateFormat that matching the _date
     * @return
     */
    public static Date stringToDate(String _date, String format) {
        if (null == format || "".equals(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    // private static String getString(byte[] b) {
    // StringBuffer sb = new StringBuffer();
    // for (int i = 0; i < b.length; i++) {
    //
    // int val = ((int) b[i]) & 0xff;
    // if (val < 16) {
    // sb.append("0");
    // }
    // sb.append(Integer.toHexString(val));
    // }
    // return sb.toString();
    // }

    /**
     * get bitmap by url
     * 
     * @param url
     * @return
     */
    public static Bitmap loadImageFromUrl(String url) {
        URL m;
        InputStream i = null;
        Bitmap d = null;
        try {
            m = new URL(url);
            i = (InputStream) m.getContent();
            d = BitmapFactory.decodeStream(i);
        } catch (Exception e1) {
            e1.printStackTrace();
        } catch (OutOfMemoryError e) {
            System.gc();
        }

        return d;
    }

    public static File convertBitmapToFile(File file, Bitmap bitmap) {
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return file;
    }

    public static Bitmap readBitmapByFile(String path,int sampleSize)
	{
		Bitmap bitmap =null;
		try
		{
			bitmap = BitmapFactory.decodeFile(path);
		}
		catch(OutOfMemoryError e)
		{
			
			bitmap = readBitmapByFile(path,sampleSize *= 2);
		}
		finally
		{
			
		}
		return bitmap; 
		
	}
    
    public static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, boolean scaleUp,
            boolean recycle) {
        int deltaX = source.getWidth() - targetWidth;
        int deltaY = source.getHeight() - targetHeight;
        if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
            /*
             * In this case the bitmap is smaller, at least in one dimension,
             * than the target. Transform it by placing as much of the image as
             * possible into the target and leaving the top/bottom or left/right
             * (or both) black.
             */
            Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b2);

            int deltaXHalf = Math.max(0, deltaX / 2);
            int deltaYHalf = Math.max(0, deltaY / 2);
            Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf + Math.min(targetWidth, source.getWidth()),
                    deltaYHalf + Math.min(targetHeight, source.getHeight()));
            int dstX = (targetWidth - src.width()) / 2;
            int dstY = (targetHeight - src.height()) / 2;
            Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight - dstY);
            c.drawBitmap(source, src, dst, null);
            if (recycle) {
                source.recycle();
            }
            return b2;
        }
        float bitmapWidthF = source.getWidth();
        float bitmapHeightF = source.getHeight();

        float bitmapAspect = bitmapWidthF / bitmapHeightF;
        float viewAspect = (float) targetWidth / targetHeight;

        if (bitmapAspect > viewAspect) {
            float scale = targetHeight / bitmapHeightF;
            if (scale < .9F || scale > 1F) {
                scaler.setScale(scale, scale);
            } else {
                scaler = null;
            }
        } else {
            float scale = targetWidth / bitmapWidthF;
            if (scale < .9F || scale > 1F) {
                scaler.setScale(scale, scale);
            } else {
                scaler = null;
            }
        }

        Bitmap b1;
        if (scaler != null) {
            // this is used for minithumb and crop, so we want to filter here.
            b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), scaler, true);
        } else {
            b1 = source;
        }

        if (recycle && b1 != source) {
            source.recycle();
        }

        int dx1 = Math.max(0, b1.getWidth() - targetWidth);
        int dy1 = Math.max(0, b1.getHeight() - targetHeight);

        Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth, targetHeight);

        if (b2 != b1) {
            if (recycle || b1 != source) {
                b1.recycle();
            }
        }

        return b2;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public static Bitmap decodeSampledBitmapFromPath(String pathName, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(pathName, options);
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    public static void saveBitmap(Bitmap bitmap, String fileName) throws IOException {
        File f = new File(fileName);
        f.createNewFile();
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (java.io.FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BitmapFactory.Options getBitmapInfo(File file)
	{
    	BitmapFactory.Options options = new BitmapFactory.Options();
    	options.inJustDecodeBounds= true;
		BitmapFactory.decodeFile(file.getAbsolutePath(), options);
		return options;
	}
    
    public static String getChannal(Context a)
    {
    	String channal = "三星";
    	 try { 
            InputStreamReader inputReader = new InputStreamReader( a.getResources().getAssets().open("config") ); 
            BufferedReader bufReader = new BufferedReader(inputReader);
            channal = bufReader.readLine();
            inputReader.close();
            bufReader.close();

        } catch (Exception e) { 
            e.printStackTrace(); 
        }
        Log.v("check channal", "channal:"+channal);
        return channal;

    }
}
